/**
 * 进行Websocket接口的类
 */
import {ConfigUtils} from "@/utils/ConfigUtils";
import {useUserStore} from "@/store/user";
import {DialogUtils} from "@/utils/DialogUtils";
import ReconnectingWebSocket from "reconnecting-websocket";

/**
 * 连接Websocket，发送消息
 */
export class TWebsocket {
    private static ws: any = null;
    static listenTaskMessage() {
        //const useTask = useTaskStore();
        if (typeof (WebSocket) == undefined) {
            DialogUtils.showErrorBox("温馨提示", "您的浏览器不支持WebSocket");
            return;
        }
        const userStore = useUserStore();
        let websocketUrl=ConfigUtils.CONFIG.baseUrl + "/wb/pipe/listen/webSocket/taskmessage";
        websocketUrl=websocketUrl.replace("https","ws").replace("http","ws");
        console.log(websocketUrl)
        TWebsocket.ws = new ReconnectingWebSocket(websocketUrl, userStore.token);

        //打开事件
        TWebsocket.ws.onopen = function() {
            console.log("websocket已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        TWebsocket.ws.onmessage = function(message: any) {
            console.log(message.data);
            //发现消息进入    开始处理前端触发逻辑
            //useTask.updateProcessInfo(JSON.parse(message.data));
        };
        //关闭事件
        TWebsocket.ws.onclose = function() {
            console.log("websocket已关闭");
            //TWebsocket.ws.close();
        };
        //发生了错误事件
        TWebsocket.ws.onerror = function() {
            console.log("websocket发生了错误");
        }
    };
    static closeListen() {
        if (TWebsocket.ws) {
            TWebsocket.ws.close();
            console.warn("websocket closed.");
        }
    }
}